import state from '../state'
import router from '../router'


let baseUrl

export async function $fetch (url, options) {
    const finalOptions = Object.assign({}, {
        headers: {
            'Content-Type': 'application/json',
        },
        credentials: 'include',
    }, options)
    const response = await fetch(`${baseUrl}${url}`, finalOptions)

    if(response.ok){
        const data = await response.json()
        return data
    } else if (response.status === 403){
        //登录会话不再有效, 退出登录
        state.user = null
        console.log('null.........')
        //如果访问的是私有路由,则跳到登录页面
        if(router.currentRoute.matched.some(r => r.meta.private)){
            console.log('fullpath.......')
            router.replace({name: 'login', params:{
                wantedRoute: router.currentRoute.fullPath,
            }})
        }
    } else {
        const message = await response.text()
        const error = new Error(message)
        throw error
    }
}


export default {
    install (Vue, options){
        baseUrl = options.baseUrl      //需要在全局定义 这个变量
        Vue.prototype.$fetch = $fetch
    }
}
